package com.example.demo.app;

import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class AppExceptionHandler {

    @ExceptionHandler(value = java.lang.Exception.class)
    @ResponseBody
    public Response handle(java.lang.Exception e) {
        if ( e instanceof BindException) {
            BindException exception = (BindException) e;
            return Response.error(ResponseEnum.UNKNOWN_ERROR.getCode(), exception.getBindingResult().getFieldError().getDefaultMessage());
        }

        if (e instanceof Exception) {
            Exception exception = (Exception) e;
            return Response.error(exception.getCode(), exception.getMessage());
        }
        // 需要报警的日志

        // 记日志
        e.printStackTrace();
        return Response.error(ResponseEnum.UNKNOWN_ERROR.getCode(), e.toString() + " " + e.getMessage());
    }
}